//
//  HLIMKitAudioCenter.m
//  YueYue
//
//  Created by hulu001 on 2024/1/11.
//

#import "HLIMKitAudioCenter.h"

@interface HLIMKitAudioCenter ()<NIMMediaManagerDelegate>
@property (strong,  nonatomic) NIMMessage *currentMessage;
@property (strong,  nonatomic) NSTimer *timer;

@end

@implementation HLIMKitAudioCenter


+ (instancetype)sharedCenter
{
    static HLIMKitAudioCenter *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[self alloc] init];
    });

    return _sharedManager;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NIMSDK sharedSDK].mediaManager addDelegate:self];
    }
    return self;
}

- (BOOL)isPlayingMessage:(id)message
{
    if (!self.currentMessage) {
        return NO;
    }
    
    NIMMessage *msg = (NIMMessage *)message;
    
    return [msg.messageId isEqualToString:self.currentMessage.messageId];
}

- (void)play:(id)message
{
    NIMMessage *msg = (NIMMessage *)message;
    self.currentMessage = msg;
    
    NIMAudioObject *object = (NIMAudioObject *)msg.messageObject;
    if (![NSFileManager.defaultManager fileExistsAtPath:object.path]) {
        [NIMSDK.sharedSDK.resourceManager download:object.url filepath:object.path progress:^(float progress) {
        } completion:^(NSError * _Nullable error) {
            [NIMSDK.sharedSDK.mediaManager play:object.path];
        }];
    } else {
        [NIMSDK.sharedSDK.mediaManager play:object.path];
    }
}

- (void)stop
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    [NIMSDK.sharedSDK.mediaManager stopPlay];
}

#pragma mark - TIOAudioDelegate

- (void)playAudio:(NSString *)filePath didCompletedWithError:(NSError *)error
{
    self.currentMessage = nil;
}

- (void)stopPlayAudio:(NSString *)filePath didCompletedWithError:(nullable NSError *)error
{
    self.currentMessage = nil;
}


@end
